<template>
  <div class="bgImg-wrapper">
    <el-form label-width="50px">
      <el-button class="mb-2 bold fs16" style="display: block;" type="primary" plain icon="el-icon-plus" @click="addBgImg">
        添加背景图
      </el-button>
      <el-row>
        <el-col :span="6" v-for="(item, i) in bgImgList" :key="i">
          <el-form-item label="名字">
            <el-input v-model="item.image_name"></el-input>
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="getAuthHeaders()"
              :data="uploadData"
              :show-file-list="false"
              :on-success="(res) => uploadSuccess(res, i)"
              :before-upload="beforeUpload"
            >
              <img v-if="item.image_url" :src="item.image_url" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button class="mr-3" size="small" type="danger" @click="delBgImg(item.id, i)">删除</el-button>
            <el-button size="small" type="primary" @click="save(i)">保存</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      uploadData: {},
      bgImgList: [
        // {id:"", image_name: "", image_url: "" }
      ],
    };
  },
  created() {
    this.fetch();
    this.$store.commit("changeBreadcrumb", this.$route);
  },
  methods: {
    addBgImg() {
      this.bgImgList.push({ id: "", image_name: "", image_url: "" });
    },
    delBgImg(id, i) {
      this.$confirm(`确定要删除吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (!id) return this.bgImgList.splice(i, 1);
          const formData = new FormData();
          formData.append("ids", [id]);
          const { data: res } = await this.$http.post("delProductImage", formData);
          // console.log(res, "删除图片返回的数据");
          if (res.code != "0") return this.$message("删除图片失败");
          this.$message.success("删除成功");
          this.fetch();
        })
        .catch(() => {});
    },
    async fetch() {
      const { data: res } = await this.$http.post("findProductImageByPage");
      // console.log(res, "获取图片返回的数据");
      if (res.code != "0") return this.$message("获取背景图片失败");
      this.bgImgList = [];
      res.data.forEach((item) => {
        const { id, image_name, image_url } = item;
        this.bgImgList.unshift({ id, image_name, image_url });
      });
      // console.log(this.bgImgList, "背景图列表");
    },
    async save(i) {
      const curr = this.bgImgList[i];
      curr.image_name = curr.image_name.trim();
      if (!curr.image_name || !curr.image_url) {
        let errorStr = curr.image_name ? "请上传图片" : "请输入图片名字";
        return this.$message.error(errorStr);
      }
      this.$confirm("确定要保存吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const formData = new FormData();
          formData.append("id", this.bgImgList[i].id);
          formData.append("image_name", this.bgImgList[i].image_name);
          formData.append("image_url", this.bgImgList[i].image_url);
          formData.append("image_status", 1);
          const { data: res } = await this.$http.post("saveProductImage", formData);
          // console.log(res, "保存图片返回的数据");
          if (res.code != "0") return this.$message("保存图片失败");
          this.$message.success("保存成功");
        })
        .catch(() => {});
    },
    async uploadSuccess(res, i) {
      // console.log(res, "上传图片");
      if (res.code != "0") return this.$message("上传图片失败");
      this.bgImgList[i].image_url = this.showImgUrl + res.data;
    },
    beforeUpload(file) {
      // console.log(file, "上传前");
      this.uploadData.files = file;
      // console.log(file.size);
      const isLt20kb = file.size / 1024 / 1024 < 0.02;
      if (!isLt20kb) {
        this.$message.error("上传头像图片大小不能超过 20 kb!");
      }
      return isLt20kb;
    },
  },
};
</script>

<style lang="scss">
.bgImg-wrapper {
  .el-form {
    .el-form-item {
      .el-form-item__content {
        line-height: normal;
      }
      .el-input {
        width: 58%;
      }
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #6c74b1;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 232px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 232px;
    display: block;
  }
  .avatar-uploader {
    .el-icon-plus:before {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
